package com.jackrain.nea.omslocal.Dao;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.omslocal.service.LocalLogService;
import com.jackrain.nea.omslocal.service.SendMqServies;
import com.jackrain.nea.omslocal.util.JsonKeyCheck;
import com.jackrain.nea.omslocal.util.RegexDateUtil;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.Tools;
import com.jackrain.nea.util.Validator;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Discription: 线下消费会员数据
 * Created with IntelliJ IDEA.
 * @Author cs
 * @Date 2017/7/25 17:40
 */
@Component
@Slf4j
public class TaoBaoMemberDao {

    @Autowired
    private RegexDateUtil regexDate;
    @Autowired
    private LocalLogService localLogService;
    private FastDateFormat fastformat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private SendMqServies sendMq;

    /**
     * 保存淘宝会员数据
     *
     * @param menberObj
     * @param topic
     * @param msgkey
     */
    public void memberStart(JSONObject menberObj, String msgkey, String topic) throws Exception {
        TaoBaoMemberDao taoBaoMemberDao = ApplicationContextHandle.getBean(TaoBaoMemberDao.class);
        PropertiesConf pconf = (PropertiesConf) ApplicationContextHandle.getBean("propertiesConf");
        log.debug(menberObj.toString());
        int countFaild = 0;

        // 定义接收消费日志信息的 jsonobject
        JSONObject infoObj = new JSONObject();
        String sellernick = menberObj.getString("nickname");
        if ("".equals(sellernick) || sellernick.isEmpty()){
            log.error("店铺昵称为空,无法插入数据 "+ msgkey );
            return;
        }
        JSONObject jsonObject1 = menberObj.getJSONObject("crm_members_get_response");

        JSONObject jsonObject2 = jsonObject1.getJSONObject("members");

        log.debug("msgkey : " + msgkey + "  " + jsonObject1.toJSONString());
        JSONArray menberArr = jsonObject2.getJSONArray("basic_member");

        if (menberArr == null || menberArr.isEmpty()) {
            // 没有数据
            log.debug("会员数据为空 " + msgkey);
            return;
        }
        // 会员没有明细表,直接新增主表或更新主表
        for (Object obj : menberArr) {

            JSONObject tempObj = null;
            try {
                // 循环遍历获取会员数据
                tempObj = JSONObject.parseObject(obj.toString(), Feature.OrderedField);
                String buyer_nick = tempObj.getString("buyer_nick");
                tempObj.put("seller_nick",sellernick);
                // 根据 buyer_nick 查询数据库,判断该数据是 新增 或是 修改
                String selectSql = "SELECT id FROM T_BOMSHOPMEMBER WHERE buyer_nick = ?";
                int id = Tools.getInt(QueryEngine.getInstance().doQueryOne(selectSql, new Object[]{buyer_nick}), -1);
                if (id < 0) {
                    // 新增数据
                    // 数据不为空 保存数据
                    taoBaoMemberDao.insert(tempObj, topic);
                } else {
                    // 根据查询到的 id 更新主表数据
                    taoBaoMemberDao.update(tempObj, id, topic);

                }
            } catch (Exception e) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                // 逐条将错误信息以消息发送到线上发送到线上
                JSONObject errObj = new JSONObject();
                errObj.put("tablename", pconf.getProperty("ons.tbrefund"));
                errObj.put("topic", topic);
                errObj.put("tag", pconf.getProperty("ons.comp"));
                errObj.put("msgkey", msgkey);
                // 线下消费报错的主机 ip
                errObj.put("client_ip", NetUtils.getLocalAddress());
                // 将错误以流写出
                e.printStackTrace(pw);
                errObj.put("errmsg", sw.toString());
                errObj.put("protime", System.currentTimeMillis());
                sendMq.sendMqinfoObj(errObj, pconf.getProperty("ons.loginfor.err.topic"), pconf.getProperty("ons.loginfor.err.tag"));

            }

        }
        // 消费回执
        infoObj.put("msgkey", msgkey);
        infoObj.put("client_ip", NetUtils.getLocalAddress());
        infoObj.put("topic", topic);
        infoObj.put("countsuccess", (menberArr.size() - countFaild));
        infoObj.put("protime", System.currentTimeMillis());
        infoObj.put("code", 0);

        sendMq.sendMqinfoObj(infoObj, pconf.getProperty("ons.loginfor.suf.topic"), pconf.getProperty("ons.loginfor.suf.tag"));

    }

    @Transactional
    public void insert(JSONObject tempObj, String topic) throws Exception {
        // 数据不为空 保存数据
        if (!tempObj.isEmpty()) {
            saveMember(tempObj);
        } else {
            log.debug("主表数据为空");
        }

    }

    @Transactional
    public void update(JSONObject tempObj, int id, String topic) throws Exception {
        // 根据查询到的 id 更新主表数据
        updateMember(tempObj, id);
    }

    /**
     * 保存会员主表
     *
     * @param jsonObj
     * @return
     * @throws SQLException
     */
    public void saveMember(JSONObject jsonObj) throws SQLException, ParseException {

        JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
        jsonObj = checkjson.checkJsonkeycache(jsonObj, "T_BOMSHOPMEMBER", checkjson.getInsertcolsmap());
        log.debug(jsonObj.toString());
        // 获取主表的 sequences
        String squnceSql = "select get_wsequences('T_BOMSHOPMEMBER') as SEQ from dual";
        Long id = TypeUtils.castToLong(QueryEngine.getInstance().doQueryOne(squnceSql));

        jsonObj.put("id", id);
        String columnName = "";
        String columnValue = "";
        Set set = jsonObj.keySet();
        Object[] objArr = jsonObj.values().toArray();

        for (Object obj1 : set) {
            columnName = columnName + "," + obj1;
        }
        columnName = columnName.substring(1);

        for (int i = 0; i < objArr.length; i++) {

            if (objArr[i] instanceof String) {
                if (regexDate.regexDate(((String) objArr[i]))) {
                    Date date = fastformat.parse(((String) objArr[i]));
                    objArr[i] = date;
                }
            }
            columnValue = columnValue + ",?";
        }

        columnValue = columnValue.substring(1);
        String sql = "insert into T_BOMSHOPMEMBER (" + columnName + ") values (" + columnValue + ")";
        int code = QueryEngine.getInstance().executeUpdate(sql, objArr);

    }


    /**
     * 更新会员主表
     *
     * @param jsonObj
     * @return
     * @throws SQLException
     */

    public void updateMember(JSONObject jsonObj, int id) throws SQLException, ParseException {
        JsonKeyCheck checkjson = ApplicationContextHandle.getBean(JsonKeyCheck.class);
        jsonObj = checkjson.checkJsonkeycache(jsonObj, "T_BOMSHOPMEMBER", checkjson.getUpdatecolsmap());
        log.debug(jsonObj.toString());

        String params = "";
        Set set = jsonObj.keySet();
        Object[] objArr = jsonObj.values().toArray();
        for (Object obj1 : set) {
            Object tempobject = jsonObj.get(obj1);
            params = params + "" + obj1 + " = ?,";
        }
        params = params.substring(0, params.length() - 1);

        for (int i = 0; i < objArr.length; i++) {

            if (Validator.isNull(objArr[i])) {
                objArr[i] = "null";
            }
            if (objArr[i] instanceof String) {
                if (regexDate.regexDate(((String) objArr[i]))) {
                    Date date2 = fastformat.parse(((String) objArr[i]));
                    objArr[i] = date2;
                }
            }
        }

        String sql = "update T_BOMSHOPMEMBER set " + params + " where id = ?";
        log.debug("======================" + jsonObj.toString());
        int code = QueryEngine.getInstance().executeUpdate(sql, ArrayUtils.add(objArr, id));

    }


}
